<script setup>
import { computed, onMounted, reactive, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

import { useInfoStoreHook } from "../../store/modules/info";
import { useDetectionStoreHook } from "../../store/modules/detection";
import useLoading from "../../utils/loading";

const info = useInfoStoreHook();
const detection = useDetectionStoreHook();

const workType = ref(3);
const workTypeDesc = computed(() => (workType.value === 3 ? "首件送检" : "过程送检"));
const dialogVisible = ref(false);
const dialogContentHeight = reactive({
  height: "100%",
  width: "100%",
  padding: "20vh 0"
});
async function recordClick() {
  // 数据完整性判定
  if (detection.inspectFields.every((item) => typeof item.value !== "number" && !item.value)) {
    ElMessageBox.alert("请至少完成一项字段填写后再进行上报！", "数据不完整", {
      type: "error",
      confirmButtonText: "OK"
    });
    return;
  }
  // for (const item of detection.inspectFields) {
  //   if (typeof item.value !== "number" && !item.value) {
  //     ElMessageBox.alert("请完成所有字段的填写后再进行上报！", "数据不完整", {
  //       type: "error",
  //       confirmButtonText: "OK"
  //     });
  //     return;
  //   }
  // }
  const loading = useLoading();
  await detection.insertData(crypto.randomUUID().toString().split("-").join(""), workType.value);
  await detection.updateDataset();
  loading.close();
}

function selectWorkType(value) {
  dialogVisible.value = false;
  workType.value = value;
}

async function delData(uuid) {
  if (info.identity < 2) return;
  ElMessageBox.alert(`确认删除该项及其相关的送检数据吗？`, "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      const loading = useLoading();
      try {
        const res = await window.api.delRemoteData(uuid);
        if (res.code !== 0) {
          ElMessage.error("删除失败，请稍后重试！");
          return;
        }
        await window.api.delLocalData(uuid);
        await detection.updateDataset();
        ElMessage.success("删除成功！");
      } finally {
        loading.close();
      }
    })
    .catch(() => {});
}

onMounted(async () => {
  dialogContentHeight.height = window.innerHeight - 60 - 48 + "px";
  window.addEventListener("resize", () => {
    dialogContentHeight.height = window.innerHeight - 60 - 48 + "px";
  });
});

// 设置滚动
const scrollBarRef = ref(null);
const selectBoxHeight = ref(0);
const mouseFlag = ref(false);
const mouseOffsetX = ref(0);
const mouseOffsetY = ref(0);

onMounted(() => {
  selectBoxHeight.value = window.innerHeight - 54 - 60;
  addEventListener("resize", () => (selectBoxHeight.value = window.innerHeight - 54 - 60));
});

function mouseDownHandler(e) {
  mouseOffsetX.value = e.clientX;
  mouseOffsetY.value = e.clientY;
  mouseFlag.value = true;
}

function mouseUpHandler() {
  mouseFlag.value = false;
}

function mouseMoveHandler(e) {
  const scrollLeft = scrollBarRef.value.wrapRef.scrollLeft;
  const scrollTop = scrollBarRef.value.wrapRef.scrollTop;
  if (mouseFlag.value) {
    scrollBarRef.value.setScrollLeft(
      scrollLeft + mouseOffsetX.value - (mouseOffsetX.value = e.clientX)
    );
    scrollBarRef.value.setScrollTop(
      scrollTop + mouseOffsetY.value - (mouseOffsetY.value = e.clientY)
    );
  }
}
</script>

<template>
  <el-scrollbar
    ref="scrollBarRef"
    class="select-box"
    :height="selectBoxHeight + 'px'"
    @mousedown="mouseDownHandler"
    @mouseup="mouseUpHandler"
    @mousemove="mouseMoveHandler"
    @mouseleave="mouseUpHandler"
  >
    <el-form class="form" label-width="124px" size="large">
      <el-row class="row" :gutter="8" style="padding: 0 16px; width: 100%">
        <el-col :sm="8" :lg="6" :xl="4">
          <el-form-item label="送检类型">
            <el-input
              v-model="workTypeDesc"
              input-style="text-align: center"
              readonly
              @click="dialogVisible = true"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="row" :gutter="8" style="padding: 0 16px; width: 100%">
        <el-col v-for="field in detection.inspectFields" :key="field.name" :sm="8" :lg="6" :xl="4">
          <el-form-item :label="field.name">
            <el-input-number v-model="field.value" :controls="false" />
          </el-form-item>
        </el-col>
        <el-col :sm="8" :lg="6" :xl="4">
          <el-button type="primary" class="btn" @click="recordClick">记 录 数 据</el-button>
        </el-col>
      </el-row>
      <el-divider content-position="left">计量送检值</el-divider>
      <div style="padding: 0 24px">
        <el-table fit stripe border :data="detection.inspects">
          <el-table-column align="center" prop="name" label="检验项目" width="140px" />
          <el-table-column align="center" prop="3" label="首检值">
            <template #default="{ row }">
              <el-tag
                v-for="data in row[3]"
                :key="data.uuid"
                class="data-tag"
                :type="data.reported ? '' : 'info'"
                size="large"
                @click="delData(data.uuid)"
                >{{ data.value }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column align="center" prop="4" label="过程送检值">
            <template #default="{ row }">
              <el-tag
                v-for="data in row[4]"
                :key="data.uuid"
                class="data-tag"
                :type="data.reported ? '' : 'info'"
                size="large"
                @click="delData(data.uuid)"
                >{{ data.value }}</el-tag
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>
  </el-scrollbar>
  <el-dialog v-model="dialogVisible" fullscreen>
    <el-row :gutter="12" :style="dialogContentHeight">
      <el-col :span="12">
        <el-button class="selection" @click="selectWorkType(3)">首件送检</el-button>
      </el-col>
      <el-col :span="12">
        <el-button class="selection" @click="selectWorkType(4)">过程送检</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<style lang="scss" scoped>
.label {
  line-height: 48px;
  margin-right: 8px;
  text-align: right;
}
.btn {
  margin-left: 32px;
  width: 120px;
  margin-bottom: 24px;
}
.selection {
  height: 100% !important;
  width: 100% !important;
  font-size: 22px !important;
}
.data-tag {
  margin: 0 2px;
  font-size: 15px;
  cursor: pointer;
}
:deep(.el-divider) {
  .el-divider__text {
    color: #888888;
  }
  margin: 8px 0 24px 0;
}
:deep(.el-dialog .el-dialog__body) {
  height: 100% !important;
}
:deep(.el-table td > .cell) {
  white-space: pre-wrap;
}
.select-box {
  .select-space {
    width: 100%;
  }
}
</style>
